package com.example.controller;

import com.alibaba.fastjson.JSONObject;
import com.example.Schedule.SimpleScheduleTask;
import com.example.common.CompanyConfigUtil;
import com.example.common.Result;
import com.example.dao.Client;
import com.example.dao.DetailInfoRequest;
import com.example.dao.Resend;
import com.example.entity.BasicInfo;
import com.example.entity.DetailInfo;
import com.example.service.InfoService;
import com.github.pagehelper.PageInfo;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Base64;
import java.util.List;
import java.util.Map;

@CrossOrigin
@RequestMapping("/user")
@RestController
public class InfoController {
    @Autowired
    public InfoService infoService;
    @Autowired
    private SimpleScheduleTask simpleScheduleTask;
    @GetMapping("/getPickingCartonDetails")
    public Result getPickingCartonDetails(@RequestParam Integer pageNum,
                                          @RequestParam Integer pageSize,
                                          @RequestParam String startDate,
                                          @RequestParam String endDate,
                                          @RequestParam (required = false) String field,
                                          @RequestParam (required = false) String name,
                                          HttpServletRequest request)
    {
        String comPartyId = (String) request.getAttribute("comPartyId");
        System.out.println("comPartyId=====>"+comPartyId);
        PageInfo<BasicInfo> info = infoService.selectPickingCartonDetails(pageNum, pageSize, name,field,startDate,endDate,comPartyId);
        return Result.success( info);
    }
    @PostMapping("/getDetailInfo")
    public Result getDetailInfo(@RequestBody DetailInfoRequest request,HttpServletRequest requestId) {
        System.out.println("request.getName()=====>"+request.getName());
        System.out.println("request.getDelvBchno(),====>"+request.getDelvBchno());
        String comPartyId = (String) requestId.getAttribute("comPartyId");
        PageInfo<DetailInfo> info = infoService.getDetailInfo(
                request.getDelvBchno(),
                request.getPageNum(),
                request.getPageSize(),
                request.getName(),
                comPartyId
        );
        return Result.success( info);
    }
    @PostMapping("/delById")
    public Result delById(@RequestBody BasicInfo info) {
        String invOwner = info.getInvOwner();
        Map<String, String> companyInfo = CompanyConfigUtil.getCompanyInfoByInvOwner(invOwner);
        infoService.delById(companyInfo, info,"");
        return Result.ok();
    }
    @PostMapping("/deleteBatch")
    public Result deleteBatch(@RequestBody List<BasicInfo> infos) {
        List<String> failedIds = new ArrayList<>();
        System.out.println("infos=========>"+JSONObject.toJSONString(infos));
        for (BasicInfo info : infos) {
            try {
                String invOwner = info.getInvOwner();
                Map<String, String> companyInfo = CompanyConfigUtil.getCompanyInfoByInvOwner(invOwner);
                infoService.delById(companyInfo, info,"");
            } catch (Exception e) {
                // 可以记录失败项的 key，比如 ID 或 delvBchno
                failedIds.add(info.getdelvBchno());
            }
        }

        if (!failedIds.isEmpty()) {
            return Result.error("部分数据删除失败");
        }
        return Result.ok();
    }

    @PostMapping("/resend")
    public Result resend(@RequestBody Resend resend) {
        Map<String, String> companyInfo = CompanyConfigUtil.getCompanyInfoByInvOwner(resend.getInv());
        System.out.println("=========>"+JSONObject.toJSONString(companyInfo));
        String s = simpleScheduleTask.queryDxm(companyInfo.get("name"), companyInfo.get("code"), resend.getInv(), companyInfo.get("opter"), companyInfo.get("opterName"), companyInfo.get("ak"), companyInfo.get("sk"),resend.getFromBillSc());
        System.out.println("s===>"+s);
        if (s.equals("成功")) {
            return Result.ok();
        }
        return Result.error("重传失败");
    }
    @PostMapping("/resendBatch")
    public Result resendBatch(@RequestBody List<Resend> resends) {
        System.out.println("resends=========>"+JSONObject.toJSONString(resends));
        List<String> failedIds = new ArrayList<>();
        for (Resend resend : resends) {
            try {
                Map<String, String> companyInfo = CompanyConfigUtil.getCompanyInfoByInvOwner(resend.getInv());
                String s = simpleScheduleTask.queryDxm(companyInfo.get("name"), companyInfo.get("code"), resend.getInv(), companyInfo.get("opter"), companyInfo.get("opterName"), companyInfo.get("ak"), companyInfo.get("sk"), resend.getFromBillSc());
            }
            catch (Exception e) {
                failedIds.add(resend.getDelvBchno());
            }
        }
        if (!failedIds.isEmpty()) {
            return Result.error("部分数据重传失败");
        }
        return Result.ok();
    }
    @GetMapping("/getResend")
    public Result getResend(@RequestParam Integer pageNum,
                            @RequestParam Integer pageSize,
                            @RequestParam (required = false) String name,
                            HttpServletRequest request){
        String comPartyId = (String) request.getAttribute("comPartyId");
        PageInfo<BasicInfo> info = infoService.getResend(pageNum, pageSize, name,comPartyId);
        return Result.success( info);

    }
    @PostMapping("/exportExcel")
    public void downloadExcel(@RequestBody BasicInfo info, HttpServletResponse response) {
        try {
            Map<String, String> companyInfo = CompanyConfigUtil.getCompanyInfoByInvOwner(info.getInvOwner());

            Object result = infoService.delById(companyInfo, info, "1");

            if (result instanceof Map<?, ?>) {
                Map<?, ?> fileMap = (Map<?, ?>) result;
                Object fileObj = fileMap.get("file");
                String filename = (String) fileMap.get("filename");

                if (fileObj == null || filename == null) {
                    throw new RuntimeException("下载失败：文件或文件名为空");
                }

                byte[] fileBytes;

                System.out.println("fileObj class: " + fileObj.getClass());
                if (fileObj instanceof byte[]) {
                    System.out.println("fileBytes length: " + ((byte[]) fileObj).length);
                } else if (fileObj instanceof String) {
                    System.out.println("base64 length: " + ((String) fileObj).length());
                }

                if (fileObj instanceof String) {
                    fileBytes = Base64.getDecoder().decode((String) fileObj);
                } else if (fileObj instanceof byte[]) {
                    fileBytes = (byte[]) fileObj;
                } else {
                    throw new RuntimeException("不支持的文件类型");
                }

                response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
                response.setHeader("Content-Disposition", "attachment; filename*=UTF-8''" + URLEncoder.encode(filename, "UTF-8"));
                OutputStream out = response.getOutputStream();
                out.write(fileBytes);
                out.flush();
                out.close();
            } else {
                response.sendError(500, "下载失败：返回结果无效");
            }

        } catch (Exception e) {
            e.printStackTrace();
            try {
                response.sendError(500, "导出失败: " + e.getMessage());
            } catch (IOException ioException) {
                ioException.printStackTrace();
            }
        }
    }

    @GetMapping("/getClient")
    public Result getClient(@RequestParam String name,HttpServletRequest request) {
        String comPartyId = (String) request.getAttribute("comPartyId");
        System.out.println("comPartyId====>"+comPartyId);
        List<Client> client = infoService.getClient(name,comPartyId);
        return Result.success(client);
    }




}
